package com.yuerlive.rainbow.controller;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mrd.game.message.HOpCodeEx;
import com.mrd.game.message.RainbowMessage;
import com.mrd.mina.MinaCallback;
import com.mrd.mina.MinaHelper;
import com.mrd.packet.Packet;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.common.ActivityStack;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.main.MainActivity;
import com.yuerlive.rainbow.module.search.SearchActivity;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CustomDialog;

import org.apache.mina.core.session.IoSession;

import javax.crypto.Mac;


/**
 * Created by xiaoyi on 2017/7/28.
 */

public class LiveRoomController implements MinaCallback {
    private static final String TAG = "LiveRoomController";
    private Context context;
    private Intent intent;

    private LiveRoomController() {
        MinaHelper.getInstance().connect(this, false);
    }

    private volatile static LiveRoomController mInstance;

    public static LiveRoomController getInstance() {
        if (mInstance == null) {
            synchronized (LiveRoomController.class) {
                if (mInstance == null) {
                    mInstance = new LiveRoomController();
                }
            }
        }
        return mInstance;
    }

    @Override
    public void onConnected(IoSession session) {

    }

    @Override
    public void onException(IoSession session, Throwable cause) {

    }

    @Override
    public void onReceiveMessage(IoSession session, Object message) {
        Packet packet = (Packet) message;
        switch (packet.getPacketId()) {
            case HOpCodeEx.GCUserStateRet:
                if (intent == null || context == null) {
                    return;
                } else {
//                    mCallback.onResult(intent);
                    try {
                        RainbowMessage.GCUserStateRet gcUserStateRet = RainbowMessage.GCUserStateRet.parseFrom((byte[]) packet.getData());
                        L.e(TAG,"gcUserStateRet " + "liveid :" + gcUserStateRet.getLiveId()
                                + "   isbanker :" + gcUserStateRet.getIsBanker()
                                + "   notsettle :" + gcUserStateRet.getNotSettleSweet()
                                + "   frzee :" + gcUserStateRet.getFreezeSweet());
                        if ((gcUserStateRet.getIsBanker() == 0 && gcUserStateRet.getFreezeSweet() <= 0 && gcUserStateRet.getNotSettleSweet() <= 0)
                                || gcUserStateRet.getLiveId() == Integer.parseInt(intent.getStringExtra("liveId"))
                                ) {
                            BaseActivity activity = ActivityStack.getTopActivity();
                            if (!(activity instanceof LiveRoomActivity)){
                                activity.startActivity(intent);
                            }
                        } else {
                            intent.putExtra("liveId", gcUserStateRet.getLiveId() + "");
                            intent.putExtra("chatroomId", gcUserStateRet.getChatRoomId() + "");
                            intent.putExtra("liveCover", gcUserStateRet.getIcon());

                            BaseActivity activity = ActivityStack.getTopActivity();
                            activity.runOnUiThread(() -> {
                                showDialog(activity);
                            });
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        BaseActivity activity = ActivityStack.getTopActivity();
                        activity.startActivity(intent);
                    }

//                    enterLiveRoom(intent);
                }
                break;
        }
    }


    private void showDialog(BaseActivity mActivity) {
        View view = View.inflate(mActivity, R.layout.layout_choose_dialog, null);
        CustomDialog inLiveDialog = new CustomDialog(mActivity, view);
        view.findViewById(R.id.btnCancel).setOnClickListener((v) -> {
            inLiveDialog.dismiss();
            release();
        });

        TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
        tvContent.setText("您正在别的直播间进行游戏,是否继续？");
        TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
        tvSure.setText("确定");
        tvSure.setOnClickListener((v) -> {
            inLiveDialog.dismiss();
            intent.putExtra("hasFreeze", true);
            mActivity.startActivity(intent);
            release();

        });
    }

    @Override
    public void onDisConnected(IoSession session) {

    }

    public void enterLiveRoom(Context context, Intent intent) {
        this.context = context;
        this.intent = intent;
        sendInLiveRequest();
    }

    private void sendInLiveRequest() {
        User user = UserProxy.getUser();
        if (user == null) return;
        RainbowMessage.CGUserState.Builder builder = RainbowMessage.CGUserState.newBuilder();
//        builder.setToken(user.getToken());
        builder.setUserId(Integer.parseInt(user.getUserId()));
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGUserState, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    private void release() {
        this.context = null;
        this.intent = null;
    }

}
